package mysql

import (
	"context"
	"gorm.io/gorm"
	"inspector/internal/model/entity"
)

type User struct {
	db *gorm.DB
}

func newUser(tx *gorm.DB) *User {
	return &User{
		db: tx,
	}
}

// Create creates the user.
func (d *User) Create(ctx context.Context, user *entity.User) error {
	return d.db.Table("app_user").Create(user).Error
}

// Update updates the user.
func (d *User) Update(ctx context.Context, user *entity.User) error {
	return d.db.Table("app_user").Save(user).Error
}

// Get gets the user by instance id.
func (d *User) Get(ctx context.Context, id string) (*entity.User, error) {
	user := &entity.User{}
	tx := d.db.Table("app_user")
	err := tx.Where("instance_id = ?", id).First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

// GetByAtomGitId gets the user by atom git id.
func (d *User) GetByAtomGitId(ctx context.Context, aid string) (*entity.User, error) {
	user := &entity.User{}
	tx := d.db.Table("app_user")
	err := tx.Where("atom_git_id = ?", aid).First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}

// GetByInstallationId gets the user by installation id.
func (d *User) GetByInstallationId(ctx context.Context, id string) (*entity.User, error) {
	user := &entity.User{}
	tx := d.db.Table("app_user")
	err := tx.Where("installation_id = ?", id).First(&user).Error
	if err != nil {
		return nil, err
	}
	return user, nil
}
